<template>
  <div class="Row_content" style="width:890px;">
    <Form inline ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
      <FormItem label="优惠券名称：" prop="couponName">
        <Input v-model="formValidate.couponName" placeholder="请输入" :maxlength="20" class='input-wid' @on-keyup='filterName' @on-blur="filterName"></Input>
      </FormItem>
      <FormItem label="类型：" prop="couponType">
        <Select v-model="formValidate.couponType" class='input-wid'>
          <Option v-for="(item, index) in couponTypeList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
      </FormItem>
      <FormItem :label="'面额(' + (formValidate.couponType === 0 ? '元' : '枚') + ')：'" prop="promotionAmount" v-show="formValidate.couponType==0 || formValidate.couponType==2">
        <Input v-model="formValidate.promotionAmount" placeholder="请输入" :maxlength="4" class='input-wid' @on-keyup="filterNum('promotionAmount')" @on-blur="filterNum('promotionAmount')"></Input>
      </FormItem>
      <FormItem label="折扣：" prop="promotionRate" v-show="formValidate.couponType==1">
        <Input v-model="formValidate.promotionRate" placeholder="请输入" :maxlength="3" class='input-wid' @on-keyup="filterRate('promotionRate')" @on-blur="rateBlur('promotionRate')"></Input>
        <span style="position:absolute;right:-20px; top:0;">折</span>
      </FormItem>
      <FormItem label="最低消费(元)：" prop="accumAmount">
        <Input v-model="formValidate.accumAmount" placeholder="请输入" :maxlength="9" class='input-wid' @on-keyup="filterNum0('accumAmount')" @on-blur="filterNum0('accumAmount')"></Input>
      </FormItem>
      <FormItem label="最高消费(元)：" prop="maxAmount" v-show="formValidate.couponType==1">
        <Input v-model="formValidate.maxAmount" placeholder="请输入" :maxlength="6" class='input-wid' @on-keyup="filterNum('maxAmount')" @on-blur="filterNum('maxAmount')"></Input>
      </FormItem>
      <FormItem label="最高折扣金额(元)：" prop="discountLimit" v-show="formValidate.couponType==1">
        <Input v-model="formValidate.discountLimit" placeholder="请输入" :maxlength="9" class='input-wid'  @on-keyup="filterNum('discountLimit')" @on-blur="filterNum('discountLimit')"></Input>
        <span style="position:absolute;right:-212px; top:0;color:#808695;">超过最高折扣金额，一律按此金额扣减</span>
      </FormItem>
      <FormItem label="有效期："  prop="expirationType">
        <Select v-model="formValidate.expirationType" class='input-wid'>
          <Option v-for="(item, index) in timeTypes" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
      </FormItem>
      <div style="display: inline-block; width:430px;" v-show="formValidate.expirationType==1"></div>
      <FormItem label="时长(天)：" prop="dayNum" v-show="formValidate.expirationType==0">
        <Input v-model="formValidate.dayNum" placeholder="请输入" :maxlength="5" class='input-wid' @on-keyup="filterNum('dayNum')" @on-blur="filterNum('dayNum')"></Input>
      </FormItem>
      <FormItem label="起始时间:" prop="startTime" v-show="formValidate.expirationType==1">
        <DatePicker v-model="formValidate.startTime" :editable="false" type="date" placeholder="请选择" class='input-wid' @on-change="activityStartChange" :options="activityStartOptions"></DatePicker>
      </FormItem>
      <FormItem label="到期时间:" prop="endTime" v-show="formValidate.expirationType==1">
        <DatePicker v-model="formValidate.endTime" :editable="false" type="date" placeholder="请选择" class='input-wid' @on-change="activityEndChange" :options="activityEndOptions"></DatePicker>
      </FormItem>
      <FormItem label="可用渠道：" prop="channel">
        <Select v-model="formValidate.channel" class='input-wid' multiple>
          <Option v-for="(item, index) in channelList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
      </FormItem>
      <FormItem label="适用产品：" prop="itemId">
        <Select v-model="formValidate.itemId" class='input-wid' multiple :disabled="formValidate.couponType === 2">
          <Option v-for="(item, index) in categoryList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
      </FormItem>
      <FormItem label="获取类型：" prop="originType">
        <Select v-model="formValidate.originType" class='input-wid'>
          <Option v-for="(item, index) in originTypeList" :value="item.value" :key="index">{{item.label}}</Option>
        </Select>
      </FormItem>
      <FormItem label="优惠券说明：" style="width: 830px">
        <Input v-model="formValidate.remark"
          type="textarea" style="width:720px"
          :autosize="{ minRows: 5, maxRows: 8 }"
          :maxlength="300"
          placeholder="请输入内容"></Input>
        <div style="text-align:right;width:720px;color:#c5c8ce;">{{formValidate.remark.length}}/300</div>
      </FormItem>
      <FormItem label="上传图片：" class="loadimg-form" prop="iconPath" style="width:830px;">
        <Row type="flex" align="top">
        <Col>
        <Upload ref="upload"
          :format="['jpg','png']"
          :max-size="500"
          :on-success="handleSuccess"
          :on-format-error="handleFormatError"
          :on-exceeded-size="handleMaxSize"
          type="drag"
          :action="$config.uploadImg"
          :show-upload-list="false"
          style="display: inline-block;width:96px">
          <img :src="formValidate.iconPath ? formValidate.iconPath : defaultUrl"
            style="display: inline-block;width:96px;height:96px;vertical-align: top;"
            alt="" />
        </Upload>
          <p v-if="formValidate.iconPath && imgloaded" class="replace_tit" @click="delHeadImage">删除</p>
        </Col>
        <Col>
        <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:16px">
          <p>支持格式：.jpg、.png</p>
          <p>大小：&lt;500KB</p>
        </div>
        </Col>
        </Row>
      </FormItem>
      <FormItem>
        <Button type="primary" class="btn" @click="handleSubmit">确定</Button>
        <Button class="btn" style="margin-left: 24px" @click="handleReset">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { mapState } from 'vuex'
import { saveCoupon } from '@/api/market/coupon.js'
import enumsMixin from '../enums.js'
export default {
  name: 'market_coupon_create',
  mixins: [enumsMixin],
  data () {
    return {
      imgloaded: false,
      defaultUrl: require('@/assets/images/add.png'),
      submitLock: false,
      formValidate: {
        couponName: '',
        couponType: 0,
        promotionAmount: '',
        promotionRate: '',
        accumAmount: '',
        maxAmount: '',
        discountLimit: '',
        expirationType: 0,
        dayNum: '',
        startTime: '',
        endTime: '',
        channel: [],
        itemId: [],
        remark: '',
        iconPath: ''
      },
      ruleValidate: {
        couponName: { required: true, message: '请填写优惠券名称', trigger: 'blur' },
        couponType: { required: true, message: '请选择优惠券类型' },
        promotionAmount: { required: true, message: '请填写面额', trigger: 'blur' },
        accumAmount: { required: true, message: '请填写最低消费', trigger: 'blur' },
        promotionRate: { required: true, message: '请填写折扣', trigger: 'blur' },
        maxAmount: { required: true, message: '请填写最高消费', trigger: 'blur' },
        discountLimit: { required: true, message: '请填写最高折扣金额', trigger: 'blur' },
        expirationType: { required: true, message: '请选择有效期' },
        dayNum: { required: true, message: '请填写时长', trigger: 'blur' },
        startTime: {
          required: true,
          message: '请选择起始时间'
        },
        endTime: {
          required: true,
          message: '请选择到期时间'
          // validator: (rule, value, callback) => {
          //   if (!new Date(this.formValidate.endTime).getTime()) {
          //     callback(new Error('请选择到期时间'))
          //   } else if (new Date(this.formValidate.startTime).getTime() > new Date(this.formValidate.endTime).getTime()) {
          //     callback(new Error('起始时间不能大于到期时间'))
          //   } else {
          //     callback()
          //   }
          // }
        },
        channel: { required: true, message: '请选择可用渠道' },
        itemId: { required: true, message: '请选择适用产品' },
        originType: { required: true, message: '请选择获取类型' },
        iconPath: { required: true, message: '请上传图片', trigger: 'change' }
      },
      activityStartOptions: {},
      activityEndOptions: {
        disabledDate (date) {
          return date.valueOf() < (new Date().getTime() - 24 * 60 * 60 * 1000)
        }
      }
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName
    }),
    couponType () {
      return this.formValidate.couponType
    },
    expirationType () {
      return this.formValidate.expirationType
    }
  },
  watch: {
    couponType (val) {
      if (val === 0 || val === 2) {
        this.ruleValidate.promotionAmount.required = true
        this.ruleValidate.promotionRate.required = false
        this.ruleValidate.maxAmount.required = false
        this.ruleValidate.discountLimit.required = false
      } else {
        this.ruleValidate.promotionAmount.required = false
        this.ruleValidate.promotionRate.required = true
        this.ruleValidate.maxAmount.required = true
        this.ruleValidate.discountLimit.required = true
      }
      if (val === 2) {
        this.formValidate.itemId = ['3']
      }
    },
    expirationType (val) {
      if (val === 0) {
        this.ruleValidate.dayNum.required = true
        this.ruleValidate.startTime.required = false
        this.ruleValidate.endTime.required = false
      } else {
        this.ruleValidate.dayNum.required = false
        this.ruleValidate.startTime.required = true
        this.ruleValidate.endTime.required = true
      }
    }
  },
  mounted () {
    this.ruleValidate.promotionRate.required = false
    this.ruleValidate.maxAmount.required = false
    this.ruleValidate.discountLimit.required = false
    this.ruleValidate.startTime.required = false
    this.ruleValidate.endTime.required = false
  },
  methods: {
    activityStartChange (time) {
      this.formValidate.startTime = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < Math.max(new Date(time).getTime() - 24 * 60 * 60 * 1000, new Date().getTime() - 24 * 60 * 60 * 1000)
        }
      }
    },
    activityEndChange (time) {
      this.formValidate.endTime = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    filterNum0 (name) {
      let val = this.formValidate[name]
      val = val.replace(/\D/g, '')
      if (val.length > 1 && val.substring(0, 1) === '0') {
        val = '0'
      }
      this.formValidate[name] = val
    },
    filterName () {
      this.formValidate.couponName = this.formValidate.couponName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    filterNum (name) {
      let val = this.formValidate[name]
      val = val.replace(/\D/g, '')
      if (val.substring(0, 1) === '0') {
        val = ''
      }
      this.formValidate[name] = val
    },
    filterRate (name) {
      let val = this.formValidate[name]
      if (val !== '' && val.substring(0, 1) === '.') {
        val = ''
      }
      val = val.replace(/^0*(0\.|[1-9])/, '$1')
      val = val.replace(/[^\d.]/g, '')
      val = val.replace(/\.{2,}/g, '.')
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      val = val.replace(/^(-)*(\d+)\.(\d).*$/, '$1$2.$3')
      if (val >= 10) {
        val = val.substring(0, val.length - 1)
      }
      if (val.indexOf('.') === 2) {
        val = val.substring(0, 2)
      }
      if (val.length === 2 && val === '00') {
        val = '0'
      }
      this.formValidate[name] = val
    },
    rateBlur (name) {
      let val = this.formValidate[name]
      if (val > 10) {
        val = val.substring(0, val.length - 1)
      }
      if (val.indexOf('.') === 1 && val.length < 3) {
        val = val.substring(0, 1)
      }
      if (val === '0' || val === '0.0') {
        val = ''
      }
      this.formValidate[name] = val
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          if (this.formValidate.promotionRate > 10) {
            this.$Message.error('折扣不能大于10')
            return
          }
          if (this.formValidate.couponType === 1) {
            if (parseInt(this.formValidate.maxAmount) <= parseInt(this.formValidate.accumAmount)) {
              this.$Message.error({
                content: '最低消费金额必须小于最高消费金额',
                duration: 3
              })
              return
            }
            if (parseInt(this.formValidate.maxAmount) <= parseInt(this.formValidate.discountLimit)) {
              this.$Message.error({
                content: '最高折扣金额必须小于最高消费金额',
                duration: 3
              })
              return
            }
          }
          if (this.formValidate.expirationType === 1) {
            if (new Date(this.formValidate.endTime).getTime() < new Date(this.formValidate.startTime).getTime()) {
              this.$Message.error('起始时间不能大于到期时间')
              return
            }
          }
          const formValidate = this.formValidate
          let extraData = {
            channel: formValidate.channel,
            itemId: formValidate.itemId,
            accumAmount: formValidate.accumAmount
          }
          let couponBase = {
            merchantId: this.merchantId,
            couponName: formValidate.couponName,
            couponType: formValidate.couponType,
            expirationType: formValidate.expirationType,
            originType: formValidate.originType,
            iconPath: formValidate.iconPath,
            remark: formValidate.remark,
            creatorId: this.userId,
            creatorName: this.userName,
            ruleSource: 1
          }
          let rules = [
            {
              matchRules: {
                channel: formValidate.channel,
                itemType: 1,
                itemId: formValidate.itemId
              },
              processRules: [
                {
                  processMethod: 0,
                  accumType: 0,
                  processTarget: 0,
                  accumAmount: formValidate.accumAmount
                }
              ]
            }
          ]
          if (formValidate.couponType === 0 || formValidate.couponType === 2) {
            extraData.promotionAmount = formValidate.promotionAmount
            rules[0].processRules[0].promotionAmount = formValidate.promotionAmount
            rules[0].processRules[0].discountType = 0
            if (formValidate.couponType === 2) {
              rules[0].processRules[0].processMethod = 1
              rules[0].processRules[0].discountType = null
            }
          } else if (formValidate.couponType === 1) {
            extraData.promotionAmount = Number(formValidate.promotionRate) * 10 / 100
            couponBase.maxAmount = formValidate.maxAmount
            rules[0].processRules[0].promotionAmount = Number(formValidate.promotionRate) * 10 / 100
            rules[0].processRules[0].discountType = 1
            rules[0].processRules[0].discountLimit = formValidate.discountLimit
          }
          if (formValidate.expirationType === 0) {
            couponBase.dayNum = formValidate.dayNum
          } else if (formValidate.expirationType === 1) {
            couponBase.startTime = formValidate.startTime + ' 00:00:00'
            couponBase.endTime = formValidate.endTime + ' 23:59:59'
          }
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          saveCoupon({
            extraData,
            merchantId: this.merchantId,
            couponBase,
            rules
          }).then(res => {
            this.submitLock = false
            const result = res.data || {}
            if (result.status === 200) {
              this.$Message.success('新增成功')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.submitLock = false
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'market_coupon_list'
        })
      })
    },
    handleMaxSize (file) {
      this.$Message.warning('上传的图片大小不能超过500k')
    },
    handleFormatError (file) {
      this.$Message.warning('上传的图片格式错误')
    },
    handleSuccess (response, file, fileList) {
      // var img = new Image()
      // img.src = response.full_img_url
      var _this = this
      // let temsrc = _this.formValidate.iconPath
      _this.formValidate.iconPath = response.full_img_url
      // img.onload = function () {
      //   if (img.width !== 128 || img.height !== 128) {
      //     _this.$Message.warning('上传的图片规格不符')
      //     _this.formValidate.iconPath = temsrc
      //   } else {
      _this.imgloaded = true
      //     _this.formValidate.iconPath = response.full_img_url
      //   }
      // }
    },
    delHeadImage () {
      this.imgloaded = false
      this.formValidate.iconPath = ''
    }
  }
}
</script>
<style scoped>
.input-wid{ width: 280px;}
.replace_tit{
    position: absolute;
    left: 0;
    top: 72px;
    width: 96px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    opacity: 0.8;
    background: #ED4014;
    color: #fff;
  }
</style>
